package com.demo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Stone
 * @date 2020/6/18 17:55
 */
@Component
public class MyZuulFilter extends ZuulFilter {
    Logger logger = LoggerFactory.getLogger(MyZuulFilter.class);

    @Override
    public String filterType() {
        // 返回当前过滤器类型
        // 可选类型包括：pre、route、post、static
        // 如果需要在目标微服务前面执行过滤操作，选用pre 类型
        String type = "pre";
        return type;
    }

    @Override
    public int filterOrder() {
        // 过滤器执行顺序
        return 0;
    }

    /**
     * @Author:Stone

       * @return: boolean
     * @Date: 2020/6/18 17:58
     * @Description: 判断是否应该过滤，返回true需要过滤，返回false不需要过滤
    */
    @Override
    public boolean shouldFilter() {
        // 1.获取当前RequestContext 对象
        // RequestContext就是通过threadLocal.get()拿的。threadLocal是一条河的话，资源就是通过get() set(),从上游飘到下游
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 2.获取request对象
        HttpServletRequest httpServletRequest = currentContext.getRequest();
        // 3.判断是否需要过滤
        String keyword = httpServletRequest.getParameter("keyword");
        return "hello".equals(keyword);
    }

    /**
     * @Author:Stone

       * @return: java.lang.Object
     * @Date: 2020/6/18 18:05
     * @Description: shouldFilter()返回true后执行的方法
    */
    @Override
    public Object run() throws ZuulException {
        logger.debug("启用Zuul过滤器！！！");
        // 官方文档说：当前实现会忽略这个返回值，所以返回null 即可
        return null;
    }
}
